package com.xmg.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.thoughtworks.xstream.XStream;
import com.xmg.model.AccessToken;
import com.xmg.model.Article;
import com.xmg.model.message.*;
import com.xmg.util.WxUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author xmg
 * @Description 公众号测试账号地址：https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
 * @email 463364973@qq.com
 * <p>
 * Date:2019/4/5 15:25
 */
@Service
public class WxService {

    private final static Logger LOGGER = LoggerFactory.getLogger(WxService.class);
    // 微信
    /** 获取accessToken地址 */
    private final static String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    /** appid */
    private final static String APP_ID = "你的appid";
    /** appsecret */
    private final static String APP_SECRET = "你的密钥";

    private static AccessToken ACCESS_TOKEN;




    /**
     * 验证签名
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean check(String signature, String timestamp, String nonce) {
        // 1）将token、timestamp、nonce三个参数进行字典序排序
        String [] strs = new String[]{WxUtil.TOKEN, timestamp, nonce};
        Arrays.sort(strs);
        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        String str = strs[0] + strs[1] + strs[2];
        String mysig = sha1(str);
        // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        return mysig.equalsIgnoreCase(signature);
    }

    /**
     * sha1加密
     * @param str
     * @return
     */
    private static String sha1(String str) {
        try {
            // 获取一个加密对象
            MessageDigest md = MessageDigest.getInstance("sha1");
            // 加密
            byte [] digest = md.digest(str.getBytes());
            char [] chars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
            StringBuilder sb = new StringBuilder();
            // 处理加密结果
            for (byte b : digest) {
                sb.append(chars[(b>>4)&15]);
                sb.append(chars[b&15]);
            }
            LOGGER.info("加密后参数：--->{}" + sb.toString());
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            LOGGER.info("sha1加密异常-->{}" + e.getMessage());
        }
        return null;
    }

    /**
     * 将微信服务发来得xml数据转为map
     * @param is
     * @return
     */
    public static Map<String,String> parseReauest(InputStream is) {
        Map<String, String> map = new HashMap<>(24);
        try {
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(is);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            // 遍历所有子节点
            for (Element e : elementList){
                map.put(e.getName(), e.getText());
            }
            // 释放资源
            is.close();
            return map;
        } catch (Exception e) {
            e.getMessage();
        }
        return null;
    }

    public static String getResponse(Map<String,String> resultMap) {
        BaseMessage msg = null;
        String msgType = resultMap.get("MsgType");
        switch (msgType){
            case "text":
                msg = dealTextMessage(resultMap);
                break;
            case "image":
                msg = dealImage(resultMap);
                break;
            case "voice":
                break;
            case "video":
                break;
            case "shortvideo":
                break;
            case "location":
                break;
            case "link":
                break;
            case "event":
                msg = dealEvent(resultMap);
                break;
                default:
                    break;
        }
        // 把消息对象处理为xml数据包
        if (msg != null){
            return  beanToXml(msg);
        }
        return  null;
    }

    /**
     * 进行图片识别
     * @param resultMap
     * @return
     */
    private static BaseMessage dealImage(Map<String,String> resultMap) {
        String picUrl = resultMap.get("PicUrl");
        String replyContent = WxUtil.BaiDuAiWord(picUrl);
        return new TextMessage(resultMap,replyContent);
    }

    /**
     * 处理事件推送
     * @param resultMap
     * @return
     */
    private static BaseMessage dealEvent(Map<String,String> resultMap) {
        String event = resultMap.get("Event");
        switch (event){
            case "CLICK":
                return dealClick(resultMap);
            case "VIEW":
                return dealView(resultMap);
                default:
                    break;
        }
        return null;
    }

    /**
     * 处理View菜单
     * @param resultMap
     * @return
     */
    private static BaseMessage dealView(Map<String,String> resultMap) {
        return null;
    }

    /**
     * 处理Click菜单
     * @param resultMap
     * @return
     */
    private static BaseMessage dealClick(Map<String,String> resultMap) {
        String eventKey = resultMap.get("EventKey");
        switch (eventKey){
            case "1":
                return new TextMessage(resultMap, "你点了一级菜单的点击菜单");
            case "32":
                return new TextMessage(resultMap,"你点我干嘛");
            default:
                break;
        }
        return null;
    }

    /**
     * 文本消息处理
     * @param resultMap
     * @return
     */
    private static BaseMessage dealTextMessage(Map<String,String> resultMap) {
        String content = resultMap.get("Content");
        if (content.equals("图文")){
            List<Article> articles = new ArrayList<>();
            articles.add(
                    new Article("高清美女图",
                    "图片来源于网络",
                    "http://mmbiz.qpic.cn/mmbiz_jpg/G7YB2TcTo2qZmuQtUnvhyAib9AJR08HH44ETK3bDLmC42IaFPgysQd4iaX82ibsW28ou7n9RMibtZMBEl2eg2lnY1A/0" ,
                    "https://btmcheck.com")
            );
            NewsMessage newsMessage = new NewsMessage(resultMap, "1", articles);
            return newsMessage;
        }
        // 智能问答机器人_千云数据
        String replyContent = WxUtil.answerRobot(content);
        TextMessage textMessage = new TextMessage(resultMap, replyContent);
        LOGGER.info("回复的消息：--->" + textMessage);
        return textMessage;
    }

    /**
     * 把消息对象处理为xml数据包
     * @param msg
     * @return
     */
    private static String beanToXml(BaseMessage msg){
        XStream xStream = new XStream();
        // 设置要处理XStrealAlias("xml")注释的类
        xStream.processAnnotations(TextMessage.class);
        xStream.processAnnotations(ImageMessage.class);
        xStream.processAnnotations(VoiceMessage.class);
        xStream.processAnnotations(VideoMessage.class);
        xStream.processAnnotations(MusicMessage.class);
        xStream.processAnnotations(NewsMessage.class);
        String xml = xStream.toXML(msg);
        LOGGER.info("XML数据：--->" + xml);
        return xml;
    }

    /**
     * 获取accessToken
     */
    private static void getToken(){
        RestTemplate restTemplate = new RestTemplate();
        String url = GET_TOKEN_URL.replace("APPID",APP_ID).replace("APPSECRET",APP_SECRET);
        String forObject = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONUtil.parseObj(forObject);
        String token = jsonObject.getStr("access_token");
        String expiresIn = jsonObject.getStr("expires_in");
        // 创建token对象,并存起来
        ACCESS_TOKEN = new AccessToken(token,expiresIn);
    }

    /**
     * 向外暴露的获取token方法
     * @return
     */
    public static String getAccessToken(){
        if (ACCESS_TOKEN == null || ACCESS_TOKEN.isExpired()){
                getToken();
        }
        return ACCESS_TOKEN.getAccessToken();
    }
}
